#!/usr/bin/ocamlrun ocaml

(*  Use Ocaml as scripting langage:        *)
(*  http://ocaml.janestreet.com/?q=node/80 *)

#use "topfind";;
#require "calendar";;
#require "sqlite3";;


let db = Sqlite3.db_open "/home/mihamina/accouting";;

(* SQLITE, extract month of date in order to have the 1rst dayt of the month *)
(* Use if the 'start of month' mofifier                                      *)
(* http://www.sqlite.org/lang_datefunc.html                                  *)

let the_query = "SELECT id, time, data_rx, data_tx FROM ifconfig WHERE time > datetime('now','start of month')";;

 
(* Convert String Option -> String *)
let so_to_strig the_so = 
  match the_so with 
    | Some s -> s;
    | _ -> "";;

(* the callback must be fun x -> x -> () *)
(* must use references to store the data *)
let l = ref [];;
let the_data_callback row headers= 
  (* row.(0) row.(1)  row.(2)  row.(3)  *)
  (* id      date     rx       tx       *)
  (* int     Date     float    float    *)
  (* "headers" is no used at the moment *)
  let the_rx = float_of_string (so_to_strig (row.(2)))
  and the_tx = float_of_string (so_to_strig (row.(3)))
  in 
   l := List.append [(the_rx +. the_tx)] !l ; 
  ()    
;;
let result = Sqlite3.exec db ~cb:the_data_callback the_query;;
let the_data = List.rev (!l);;

(* the eth0 RX or TX counter might reset, driving to counter mess   *)
(* Ex: [1;2;3;4;5;2;3;4;5;2;5;...]                                  *)
(* We need to check ranking by comparing "the_headd" and "previous" *)
let rec sum_up accumulator previous a_list = match a_list with 
  | [] -> accumulator;
  | the_head::tail -> 
    ( match the_head > previous with
      | true  -> sum_up (accumulator +. (the_head -. previous)) the_head tail
      | false -> sum_up (accumulator +. (the_head))             the_head tail
    );;
 
let final_results = sum_up 0.0 0.0 the_data;;

let () =
  try
    ( 
      match Sys.argv.(1) with 
        | "config" ->  (* sometimes there is a "config" command line argument *)
          Printf.printf "graph_title Traffic UP plus DOWN\n";
          Printf.printf "graph_vlabel traffic\n";
          Printf.printf "graph_args --base 1000 -l 3000000000\n";
          Printf.printf "traffic.label traffic\n";
          Printf.printf "graph_scale no\n";
          Printf.printf "graph_category network\n";
          Printf.printf "traffic.warning 2800000000\n";
          Printf.printf "traffic.critical 2900000000\n";
        | _ ->
          Printf.printf "";
    )
  with _ ->            (* sometimes, it's just called without any command line arguments *)
    (
      Printf.printf "traffic.value %f \n" final_results;
    )
;;
